export const request = function ({ url, method, data }) {
  let res = {}
  if (url !== '') {
    if (method === 'get') {
      if (data) {
        const paramsArray = []
        // 拼接参数
        Object.keys(data).forEach(key => paramsArray.push(key + '=' + data[key]))
        if (url.search(/\?/) === -1) {
          url += '?' + paramsArray.join('&')
        } else {
          url += '&' + paramsArray.join('&')
        }
      }
      res = fetch(url, {
        method: 'GET',
        mode: 'cors',
        headers: {
          'Content-Type': 'application/json'
        }
      }).then((response) => response.json())
        .then((json) => {
          if (json.code === 200) {
            return json.data
          }
        })
        .catch((error) => {
          return error
        })
    } else {
      if (data) {
        res = fetch(url, {
          method: method,
          mode: 'cors',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        }).then((response) => response.json())
          .then((json) => {
            if (json.code === 200) {
              return json.data
            }
          })
          .catch((error) => {
            return error
          })
      }
    }
  }
  return res
}
